package com.bawei.module_home.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_home.R
import com.bawei.module_home.model.StatusModel

class StatusAdapter(
    private val dataList: MutableList<StatusModel>,
    private val onItemClickListener: (Int) -> Unit // 点击事件回调
) : RecyclerView.Adapter<StatusAdapter.StatusViewHolder>() {
    inner class StatusViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvStatus: TextView = itemView.findViewById(R.id.tv_status)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StatusViewHolder {
        val itemView = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_status, parent, false)
        return StatusViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: StatusViewHolder, position: Int) {
        val item = dataList[position]
        holder.tvStatus.text = item.statusText
        holder.tvStatus.isSelected = item.isSelected // 设置选中状态，关联背景和文字颜色

        holder.itemView.setOnClickListener {
            // 先将之前选中的项取消选中
            val previouslySelectedPosition = dataList.indexOfFirst { it.isSelected }
            if (previouslySelectedPosition != -1 && previouslySelectedPosition != position) {
                dataList[previouslySelectedPosition].isSelected = false
                notifyItemChanged(previouslySelectedPosition)
            }
            // 设置当前项为选中
            item.isSelected = true
            notifyItemChanged(position)
            onItemClickListener.invoke(position) // 回调点击事件
        }
    }

    override fun getItemCount(): Int = dataList.size
}